<script>
  import { DateTime } from 'luxon';
  import { page } from '$app/state';
  import ActiveChannel from '$lib/components/ActiveChannel.svelte';
  import MessageInput from '$lib/components/MessageInput.svelte';
  import { runs } from '$lib/runs.js';
  import * as api from '$lib/apiServer';

  const { data } = $props();
  const { session, outbox } = data;
  let activeChannel;

  const channel = $derived(page.params.channel);
  const messages = $derived(session.messages.filter((message) => message.channel === channel));
  const messageRuns = $derived(runs(messages, session.currentUser));

  function inView(parentElement, element) {
    const parRect = parentElement.getBoundingClientRect();
    const parentTop = parRect.top;
    const parentBottom = parRect.bottom;

    const elRect = element.getBoundingClientRect();
    const elementTop = elRect.top;
    const elementBottom = elRect.bottom;

    return parentTop < elementTop && parentBottom > elementBottom;
  }

  function getLastVisibleMessage() {
    if (activeChannel) {
      const childElements = activeChannel.getElementsByClassName('message');
      const lastInView = Array.from(childElements)
        .reverse()
        .find((el) => {
          return inView(activeChannel, el);
        });
      return lastInView;
    }
  }

  function setLastRead() {
    const lastInView = getLastVisibleMessage();
    if (lastInView) {
      const at = DateTime.fromISO(lastInView.dataset.at);
      session.local.updateLastReadAt(channel, at);
    }
  }

  $effect(() => {
    const _ = session.messages;
    setLastRead();
  });

  function handleKeydown(event) {
    if (event.key === 'Escape') {
      setLastRead(); // TODO: pass in "last message DT"?
    }
  }

  let lastReadCallback = null;

  function onscroll() {
    clearTimeout(lastReadCallback); // Fine if lastReadCallback is null still.
    lastReadCallback = setTimeout(setLastRead, 2 * 1000);
  }

  async function sendMessage(message) {
    outbox.send(channel, message);
  }

  async function deleteMessage(id) {
    await api.deleteMessage(id);
  }
</script>

<svelte:window onkeydown={handleKeydown} />

<div class="active-channel" {onscroll} bind:this={activeChannel}>
  <ActiveChannel {messageRuns} {deleteMessage} />
</div>
<div class="create-message">
  <MessageInput {sendMessage} />
</div>
